<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>试剂列表</title>
    <!-- Bootstrap 5 CSS -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link href="css/bootstrap-icons.css" rel="stylesheet">
    <!-- 自定义样式 -->
    <link rel="stylesheet" href="css/style.css">
    <style>
        /* 固定操作列样式 */
        .table-responsive-wrapper {
            overflow-x: auto;
            position: relative;
        }
        
        .data-table {
            min-width: 1200px; /* 确保表格有最小宽度 */
        }
        
        .sticky-actions {
            position: sticky;
            right: 0;
            background-color: #fff;
            border-left: 1px solid #dee2e6;
            z-index: 10;
            min-width: 120px;
            width: 120px;
        }
        
        /* 为了确保操作列在深色模式下也能正常显示 */
        .table-hover tbody tr:hover .sticky-actions {
            background-color: var(--bs-table-hover-bg, #f8f9fa);
        }
        
        /* 操作列内容居中 */
        .sticky-actions {
            text-align: center;
        }
        
        /* 确保操作按钮在固定列中正常显示 */
        .action-buttons-cell {
            white-space: nowrap;
            text-align: center;
            position: sticky;
            right: 0;
            background-color: #fff;
            z-index: 999;
        }
        
        /* 鼠标悬停时保持背景色一致 */
        .table-hover tbody tr:hover .action-buttons-cell {
            background-color: var(--bs-table-hover-bg, #f8f9fa);
        }
        
        /* 滚动条样式优化 */
        .table-responsive-wrapper::-webkit-scrollbar {
            height: 8px;
        }
        
        .table-responsive-wrapper::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 4px;
        }
        
        .table-responsive-wrapper::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 4px;
        }
        
        .table-responsive-wrapper::-webkit-scrollbar-thumb:hover {
            background: #a8a8a8;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark navbar-custom">
        <div class="container-fluid">
            <a class="navbar-brand" href="#">实验室管理系统</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link active" href="page1.html">试剂列表</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="page2.html">试剂使用列表</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="page3.html">实验室预警信息看板</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="page4.html">试剂到期预警</a>
                    </li>
                </ul>
                <!-- 用户信息和退出登录 -->
                <div class="dropdown">
                    <a class="nav-link dropdown-toggle text-white" href="#" id="userDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                        <i class="bi bi-person-circle me-1"></i>
                        <span id="currentUserName">加载中...</span>
                    </a>
                    <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="userDropdown">
                        <li><a class="dropdown-item" href="#" id="logoutBtn"><i class="bi bi-box-arrow-right me-2"></i>退出登录</a></li>
                    </ul>
                </div>
            </div>
        </div>
    </nav>

    <!-- 主要内容 -->
    <div class="container-fluid">
        <div class="main-content">
            <!-- 页面标题 -->
            <div class="page-header">
                <h3 class="page-title">试剂列表</h3>
            </div>

            <!-- 搜索区域 - 暂时注释 -->
            <!--
            <div class="search-section">
                <div class="row g-3">
                    <div class="col-md-3">
                        <label for="searchName" class="form-label">物料名称</label>
                        <input type="text" class="form-control" id="searchName" placeholder="输入物料名称">
                    </div>
                    <div class="col-md-3">
                        <label for="searchCode" class="form-label">物料编码</label>
                        <input type="text" class="form-control" id="searchCode" placeholder="输入物料编码">
                    </div>
                    <div class="col-md-3">
                        <label for="searchExpiryDate" class="form-label">到期日期</label>
                        <input type="date" class="form-control" id="searchExpiryDate">
                    </div>
                    <div class="col-md-3 d-flex align-items-end">
                        <button type="button" class="btn btn-outline-primary search-btn" onclick="searchData()">
                            搜索
                        </button>
                    </div>
                </div>
            </div>
            -->

            <!-- 操作按钮 -->
            <div class="action-buttons">
                <button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#addModal">
                    新增
                </button>
                <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#importModal">
                    导入
                </button>
            </div>

            <!-- 数据表格 -->
            <div class="table-container">
                <div class="table-responsive-wrapper">
                    <table class="table table-hover data-table">
                        <thead>
                            <tr>
                                <th class="col-index">序号</th>
                                <th class="col-supplier">供应商</th>
                                <th class="col-material-code">物料编码</th>
                                <th class="col-material-name">物料名称</th>
                                <th class="col-specification">规格型号</th>
                                <th class="col-unit">单位</th>
                                <th class="col-batch">批次</th>
                                <th class="col-quantity">数量</th>
                                <th class="col-arrival-date">到货日期</th>
                                <th class="col-clone-number">克隆号</th>
                                <th class="col-expiry-date">到期日期</th>
                                <th class="col-actions sticky-actions">操作</th>
                            </tr>
                        </thead>
                        <tbody id="dataTableBody">
                            <!-- 数据将通过JavaScript动态加载 -->
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- 分页 -->
            <div class="pagination-container">
                <div class="d-flex justify-content-between align-items-center">
                    <div class="pagination-info">
                        <span id="paginationInfo">显示 0-0 条，共 0 条记录</span>
                    </div>
                    <nav aria-label="分页导航">
                        <ul class="pagination pagination-sm mb-0" id="pagination">
                            <!-- 分页按钮将通过JavaScript动态生成 -->
                        </ul>
                    </nav>
                </div>
            </div>
        </div>
    </div>

    <!-- 新增模态框 -->
    <div class="modal fade" id="addModal" tabindex="-1" aria-labelledby="addModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addModalLabel">新增试剂</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
                </div>
                <div class="modal-body">
                    <form id="addForm">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label for="addSupplier" class="form-label">供应商</label>
                                <input type="text" class="form-control" id="addSupplier" required>
                            </div>
                            <div class="col-md-6">
                                <label for="addMaterialCode" class="form-label">物料编码</label>
                                <input type="text" class="form-control" id="addMaterialCode" required>
                            </div>
                            <div class="col-md-6">
                                <label for="addMaterialName" class="form-label">物料名称</label>
                                <input type="text" class="form-control" id="addMaterialName" required>
                            </div>
                            <div class="col-md-6">
                                <label for="addSpecification" class="form-label">规格型号</label>
                                <input type="text" class="form-control" id="addSpecification" required>
                            </div>
                            <div class="col-md-6">
                                <label for="addUnit" class="form-label">单位</label>
                                <input type="text" class="form-control" id="addUnit" required>
                            </div>
                            <div class="col-md-6">
                                <label for="addBatchNumber" class="form-label">批次</label>
                                <input type="text" class="form-control" id="addBatchNumber" required>
                            </div>
                            <div class="col-md-6">
                                <label for="addQuantity" class="form-label">数量</label>
                                <input type="number" class="form-control" id="addQuantity" required>
                            </div>
                            <div class="col-md-6">
                                <label for="addArrivalDate" class="form-label">到货日期</label>
                                <input type="date" class="form-control" id="addArrivalDate" required>
                            </div>
                            <div class="col-md-6">
                                <label for="addCloneNumber" class="form-label">克隆号</label>
                                <input type="text" class="form-control" id="addCloneNumber">
                            </div>
                            <div class="col-md-6">
                                <label for="addExpiryDate" class="form-label">到期日期</label>
                                <input type="date" class="form-control" id="addExpiryDate">
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="bi bi-x-circle me-1"></i>取消
                    </button>
                    <button type="button" class="btn btn-success" onclick="saveData()">
                        <i class="bi bi-check-circle me-1"></i>保存
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑模态框 -->
    <div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editModalLabel">编辑试剂</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
                </div>
                <div class="modal-body">
                    <form id="editForm">
                        <input type="hidden" id="editId">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label for="editSupplier" class="form-label">供应商</label>
                                <input type="text" class="form-control" id="editSupplier" required>
                            </div>
                            <div class="col-md-6">
                                <label for="editMaterialCode" class="form-label">物料编码</label>
                                <input type="text" class="form-control" id="editMaterialCode" required>
                            </div>
                            <div class="col-md-6">
                                <label for="editMaterialName" class="form-label">物料名称</label>
                                <input type="text" class="form-control" id="editMaterialName" required>
                            </div>
                            <div class="col-md-6">
                                <label for="editSpecification" class="form-label">规格型号</label>
                                <input type="text" class="form-control" id="editSpecification" required>
                            </div>
                            <div class="col-md-6">
                                <label for="editUnit" class="form-label">单位</label>
                                <input type="text" class="form-control" id="editUnit" required>
                            </div>
                            <div class="col-md-6">
                                <label for="editBatchNumber" class="form-label">批次</label>
                                <input type="text" class="form-control" id="editBatchNumber" required>
                            </div>
                            <div class="col-md-6">
                                <label for="editQuantity" class="form-label">数量</label>
                                <input type="number" class="form-control" id="editQuantity" required>
                            </div>
                            <div class="col-md-6">
                                <label for="editArrivalDate" class="form-label">到货日期</label>
                                <input type="date" class="form-control" id="editArrivalDate" required>
                            </div>
                            <div class="col-md-6">
                                <label for="editCloneNumber" class="form-label">克隆号</label>
                                <input type="text" class="form-control" id="editCloneNumber">
                            </div>
                            <div class="col-md-6">
                                <label for="editExpiryDate" class="form-label">到期日期</label>
                                <input type="date" class="form-control" id="editExpiryDate">
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        取消
                    </button>
                    <button type="button" class="btn btn-primary" onclick="updateData()">
                        更新
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 导入模态框 -->
    <div class="modal fade" id="importModal" tabindex="-1" aria-labelledby="importModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="importModalLabel"><i class="bi bi-upload me-2"></i>导入数据</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
                </div>
                <div class="modal-body">
                    <div class="file-upload-area">
                        <div class="file-upload-icon">
                            <i class="bi bi-cloud-upload"></i>
                        </div>
                        <h6 class="mb-3">选择Excel文件上传</h6>
                        <input type="file" class="form-control" id="importFile" accept=".xlsx,.xls">
                        <div class="mt-3">
                            <small class="text-muted">
                                支持 .xlsx 和 .xls 格式文件<br>
                                <a href="templates/excel_template_guide.html" target="_blank" class="text-decoration-none">
                                    <i class="bi bi-info-circle me-1"></i>查看Excel模板格式说明
                                </a>
                            </small>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="bi bi-x-circle me-1"></i>取消
                    </button>
                    <button type="button" class="btn btn-primary" onclick="importData()">
                        <i class="bi bi-upload me-1"></i>导入
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap 5 JS -->
    <script src="js/bootstrap.bundle.min.js"></script>
    <!-- 自定义JavaScript -->
    <script src="js/common.js"></script>
    <script>
        let currentPage = 1;
        let pageSize = 10;
        let totalPages = 0;

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadData();
        });

        // 加载数据
        function loadData(page = 1) {
            currentPage = page;
            
            // 搜索功能暂时注释
            /*
            const searchName = document.getElementById('searchName').value.trim();
            const searchCode = document.getElementById('searchCode').value.trim();
            const searchExpiryDate = document.getElementById('searchExpiryDate').value.trim();
            */
            
            // 获取当前用户
            const currentUser = Auth.getCurrentUser();
            
            const params = {
                page: 'page1',
                pageNum: page,
                pageSize: pageSize
            };
            
            // 搜索参数暂时注释
            /*
            const searchName = document.getElementById('searchName').value.trim();
            const searchCode = document.getElementById('searchCode').value.trim();
            const searchExpiryDate = document.getElementById('searchExpiryDate').value.trim();
            if (searchName) params.material_name = searchName;
            if (searchCode) params.material_code = searchCode;
            if (searchExpiryDate) params.expiry_date = searchExpiryDate;
            */
            
            Http.get('/api/data', params)
                .then(data => {
                    if (data.success) {
                        displayData(data.data);
                        updatePagination(data.pagination);
                    } else {
                        showAlert('error', '加载数据失败: ' + data.message);
                    }
                })
                .catch(error => {
                    showAlert('error', '网络错误: ' + error.message);
                });
        }

        // 显示数据
        function displayData(data) {
            const tbody = document.getElementById('dataTableBody');
            tbody.innerHTML = '';
            
            data.forEach((item, index) => {
                const startIndex = (currentPage - 1) * pageSize;
                const row = `
                    <tr class="fade-in">
                        <td>${startIndex + index + 1}</td>
                        <td>${item.supplier || '-'}</td>
                        <td>${item.material_code || '-'}</td>
                        <td>${item.material_name || '-'}</td>
                        <td>${item.specification || '-'}</td>
                        <td>${item.unit || '-'}</td>
                        <td>${item.batch_number || '-'}</td>
                        <td>${item.quantity || '-'}</td>
                        <td>${item.arrival_date || '-'}</td>
                        <td>${item.clone_number || '-'}</td>
                        <td>${item.expiry_date || '-'}</td>
                        <td class="action-buttons-cell">
                            <a href="javascript:void(0)" class="btn-text btn-edit" onclick="editData(${item.id})">编辑</a>
                            <a href="javascript:void(0)" class="btn-text btn-delete" onclick="deleteData(${item.id})">删除</a>
                        </td>
                    </tr>
                `;
                tbody.innerHTML += row;
            });
        }

        // 更新分页
        function updatePagination(pagination) {
            totalPages = pagination.totalPages;
            const paginationElement = document.getElementById('pagination');
            const paginationInfo = document.getElementById('paginationInfo');
            
            // 更新信息
            const startRecord = (currentPage - 1) * pageSize + 1;
            const endRecord = Math.min(currentPage * pageSize, pagination.total);
            paginationInfo.textContent = `显示 ${startRecord}-${endRecord} 条，共 ${pagination.total} 条记录`;
            
            // 生成分页按钮
            let paginationHTML = '';
            
            // 上一页
            if (currentPage > 1) {
                // paginationHTML += `<li class="page-item"><a class="page-link" href="javascript:void(0)" onclick="loadData(${currentPage - 1})"><i class="bi bi-chevron-left"></i></a></li>`;
            } else {
                // paginationHTML += `<li class="page-item disabled"><span class="page-link"><i class="bi bi-chevron-left"></i></span></li>`; 
            }
            
            // 页码
            for (let i = 1; i <= totalPages; i++) {
                if (i === currentPage) {
                    paginationHTML += `<li class="page-item active"><span class="page-link">${i}</span></li>`;
                } else {
                    paginationHTML += `<li class="page-item"><a class="page-link" href="javascript:void(0)" onclick="loadData(${i})">${i}</a></li>`;
                }
            }
            
            // 下一页
            if (currentPage < totalPages) {
                // paginationHTML += `<li class="page-item"><a class="page-link" href="javascript:void(0)" onclick="loadData(${currentPage + 1})"><i class="bi bi-chevron-right"></i></a></li>`;
            } else {
                // paginationHTML += `<li class="page-item disabled"><span class="page-link"><i class="bi bi-chevron-right"></i></span></li>`; 
            }
            
            paginationElement.innerHTML = paginationHTML;
        }

        // 搜索数据 - 暂时注释
        /*
        function searchData() {
            loadData(1);
        }
        */

        // 保存数据
        function saveData() {
            // 表单验证
            const supplier = document.getElementById('addSupplier').value.trim();
            const materialCode = document.getElementById('addMaterialCode').value.trim();
            const materialName = document.getElementById('addMaterialName').value.trim();
            const specification = document.getElementById('addSpecification').value.trim();
            const unit = document.getElementById('addUnit').value.trim();
            const batchNumber = document.getElementById('addBatchNumber').value.trim();
            const quantity = document.getElementById('addQuantity').value.trim();
            const arrivalDate = document.getElementById('addArrivalDate').value.trim();
            
            // 必填字段验证
            if (!supplier) {
                showAlert('warning', '请填写供应商');
                return;
            }
            if (!materialCode) {
                showAlert('warning', '请填写物料编码');
                return;
            }
            if (!materialName) {
                showAlert('warning', '请填写物料名称');
                return;
            }
            if (!specification) {
                showAlert('warning', '请填写规格型号');
                return;
            }
            if (!unit) {
                showAlert('warning', '请填写单位');
                return;
            }
            if (!batchNumber) {
                showAlert('warning', '请填写批次');
                return;
            }
            if (!quantity || isNaN(quantity) || parseInt(quantity) <= 0) {
                showAlert('warning', '请填写有效的数量');
                return;
            }
            if (!arrivalDate) {
                showAlert('warning', '请选择到货日期');
                return;
            }
            
            // 字段长度验证
            if (supplier.length > 100) {
                showAlert('warning', '供应商名称不能超过100个字符');
                return;
            }
            if (materialCode.length > 50) {
                showAlert('warning', '物料编码不能超过50个字符');
                return;
            }
            if (materialName.length > 100) {
                showAlert('warning', '物料名称不能超过100个字符');
                return;
            }
            
            // 特殊字符验证
            const specialChars = /[<>'"&]/;
            if (specialChars.test(supplier) || specialChars.test(materialCode) || 
                specialChars.test(materialName) || specialChars.test(specification) || 
                specialChars.test(unit) || specialChars.test(batchNumber)) {
                showAlert('warning', '输入内容不能包含特殊字符 < > \' " &');
                return;
            }

            const data = {
                supplier: supplier,
                material_code: materialCode,
                material_name: materialName,
                specification: specification,
                unit: unit,
                batch_number: batchNumber,
                quantity: parseInt(quantity),
                arrival_date: arrivalDate,
                clone_number: document.getElementById('addCloneNumber').value.trim(),
                expiry_date: document.getElementById('addExpiryDate').value.trim()
            };

            Http.post('/api/data?page=page1', data)
            .then(result => {
                if (result.success) {
                    showAlert('success', '数据保存成功');
                    bootstrap.Modal.getInstance(document.getElementById('addModal')).hide();
                    document.getElementById('addForm').reset();
                    loadData(currentPage);
                } else {
                    showAlert('error', '保存失败: ' + result.message);
                }
            })
            .catch(error => {
                showAlert('error', '网络错误: ' + error.message);
            });
        }

        // 编辑数据
        function editData(id) {
            // 获取当前用户
            const currentUser = Auth.getCurrentUser();
            
            Http.get('/api/data', {page: 'page1', id: id})
                .then(data => {
                    if (data.success && data.data.length > 0) {
                        const item = data.data[0];
                        document.getElementById('editId').value = item.id;
                        document.getElementById('editSupplier').value = item.supplier || '';
                        document.getElementById('editMaterialCode').value = item.material_code || '';
                        document.getElementById('editMaterialName').value = item.material_name || '';
                        document.getElementById('editSpecification').value = item.specification || '';
                        document.getElementById('editUnit').value = item.unit || '';
                        document.getElementById('editBatchNumber').value = item.batch_number || '';
                        document.getElementById('editQuantity').value = item.quantity || '';
                        document.getElementById('editArrivalDate').value = item.arrival_date || '';
                        document.getElementById('editCloneNumber').value = item.clone_number || '';
                        document.getElementById('editExpiryDate').value = item.expiry_date || '';
                        
                        const editModal = new bootstrap.Modal(document.getElementById('editModal'));
                        editModal.show();
                    } else {
                        showAlert('error', '获取数据失败');
                    }
                })
                .catch(error => {
                    showAlert('error', '网络错误: ' + error.message);
                });
        }

        // 更新数据
        function updateData() {
            const id = document.getElementById('editId').value;
            
            // 表单验证（复用saveData的验证逻辑）
            const supplier = document.getElementById('editSupplier').value.trim();
            const materialCode = document.getElementById('editMaterialCode').value.trim();
            const materialName = document.getElementById('editMaterialName').value.trim();
            const specification = document.getElementById('editSpecification').value.trim();
            const unit = document.getElementById('editUnit').value.trim();
            const batchNumber = document.getElementById('editBatchNumber').value.trim();
            const quantity = document.getElementById('editQuantity').value.trim();
            const arrivalDate = document.getElementById('editArrivalDate').value.trim();
            
            // 必填字段验证
            if (!supplier) {
                showAlert('warning', '请填写供应商');
                return;
            }
            if (!materialCode) {
                showAlert('warning', '请填写物料编码');
                return;
            }
            if (!materialName) {
                showAlert('warning', '请填写物料名称');
                return;
            }
            if (!specification) {
                showAlert('warning', '请填写规格型号');
                return;
            }
            if (!unit) {
                showAlert('warning', '请填写单位');
                return;
            }
            if (!batchNumber) {
                showAlert('warning', '请填写批次');
                return;
            }
            if (!quantity || isNaN(quantity) || parseInt(quantity) <= 0) {
                showAlert('warning', '请填写有效的数量');
                return;
            }
            if (!arrivalDate) {
                showAlert('warning', '请选择到货日期');
                return;
            }
            
            // 字段长度验证
            if (supplier.length > 100) {
                showAlert('warning', '供应商名称不能超过100个字符');
                return;
            }
            if (materialCode.length > 50) {
                showAlert('warning', '物料编码不能超过50个字符');
                return;
            }
            if (materialName.length > 100) {
                showAlert('warning', '物料名称不能超过100个字符');
                return;
            }
            
            // 特殊字符验证
            const specialChars = /[<>'"&]/;
            if (specialChars.test(supplier) || specialChars.test(materialCode) || 
                specialChars.test(materialName) || specialChars.test(specification) || 
                specialChars.test(unit) || specialChars.test(batchNumber)) {
                showAlert('warning', '输入内容不能包含特殊字符 < > \' " &');
                return;
            }
            
            // 获取当前用户
            const currentUser = Auth.getCurrentUser();
            
            const data = {
                supplier: supplier,
                material_code: materialCode,
                material_name: materialName,
                specification: specification,
                unit: unit,
                batch_number: batchNumber,
                quantity: parseInt(quantity),
                arrival_date: arrivalDate,
                clone_number: document.getElementById('editCloneNumber').value.trim(),
                expiry_date: document.getElementById('editExpiryDate').value.trim(),
                user_id: currentUser
            };

            Http.put(`/api/data?page=page1&id=${id}`, data)
            .then(result => {
                if (result.success) {
                    showAlert('success', '数据更新成功');
                    bootstrap.Modal.getInstance(document.getElementById('editModal')).hide();
                    loadData(currentPage);
                } else {
                    showAlert('error', '更新失败: ' + result.message);
                }
            })
            .catch(error => {
                showAlert('error', '网络错误: ' + error.message);
            });
        }

        // 删除数据
        function deleteData(id) {
            if (confirm('确定要删除这条记录吗？')) {
                // 获取当前用户
                const currentUser = Auth.getCurrentUser();
                
                Http.delete(`/api/data?page=page1&id=${id}`)
                .then(result => {
                    if (result.success) {
                        showAlert('success', '删除成功');
                        loadData(currentPage);
                    } else {
                        showAlert('error', '删除失败: ' + result.message);
                    }
                })
                .catch(error => {
                    showAlert('error', '网络错误: ' + error.message);
                });
            }
        }

        // 导入数据
        function importData() {
            const fileInput = document.getElementById('importFile');
            const file = fileInput.files[0];
            
            if (!file) {
                showAlert('warning', '请选择要导入的文件');
                return;
            }
            
            const formData = new FormData();
            formData.append('file', file);
            
            // 获取当前用户（只通过URL参数传递，不在FormData中重复添加）
            const currentUser = Auth.getCurrentUser();
            
            const importBtn = document.querySelector('#importModal .btn-primary');
            const originalText = importBtn.innerHTML;
            importBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>导入中...';
            importBtn.disabled = true;
            
            fetch(`/api/upload-excel?page=page1&user_id=${encodeURIComponent(currentUser)}`, {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    showAlert('success', `导入成功！成功导入 ${result.data.success} 条记录，跳过重复 ${result.data.duplicate} 条记录`);
                    bootstrap.Modal.getInstance(document.getElementById('importModal')).hide();
                    fileInput.value = '';
                    loadData(currentPage);
                } else {
                    showAlert('error', '导入失败: ' + result.message);
                }
            })
            .catch(error => {
                showAlert('error', '网络错误: ' + error.message);
            })
            .finally(() => {
                importBtn.innerHTML = originalText;
                importBtn.disabled = false;
            });
        }

        // 显示提示信息
        function showAlert(type, message) {
            // 创建 toast 提示
            const toastContainer = document.getElementById('toastContainer') || createToastContainer();
            const toast = document.createElement('div');
            toast.className = `toast align-items-center text-white bg-${type === 'error' ? 'danger' : type === 'warning' ? 'warning' : 'success'} border-0`;
            toast.setAttribute('role', 'alert');
            toast.innerHTML = `
                <div class="d-flex">
                    <div class="toast-body">
                        <i class="bi bi-${type === 'error' ? 'exclamation-triangle' : type === 'warning' ? 'exclamation-circle' : 'check-circle'} me-2"></i>
                        ${message}
                    </div>
                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
                </div>
            `;
            
            toastContainer.appendChild(toast);
            const bsToast = new bootstrap.Toast(toast);
            bsToast.show();
            
            // 自动移除
            toast.addEventListener('hidden.bs.toast', () => {
                toast.remove();
            });
        }

        // 创建 toast 容器
        function createToastContainer() {
            const container = document.createElement('div');
            container.id = 'toastContainer';
            container.className = 'toast-container position-fixed top-0 end-0 p-3';
            container.style.zIndex = '9999';
            document.body.appendChild(container);
            return container;
        }
        
        // 初始化用户信息
        function initUserInfo() {
            const currentUser = Auth.getCurrentUser();
            if (currentUser) {
                document.getElementById('currentUserName').textContent = currentUser;
            }
        }
        
        // 添加退出登录事件
        document.getElementById('logoutBtn').addEventListener('click', function(e) {
            e.preventDefault();
            Auth.logout();
        });
        
        // 页面加载完成后初始化用户信息
        document.addEventListener('DOMContentLoaded', function() {
            initUserInfo();
        });
    </script>
</body>
</html>